// backend/src/services/device/connectionManager.js
class DeviceConnectionManager {
    constructor(wss, redis) {
        this.wss = wss;
        this.redis = redis;
        this.connections = new Map();
        this.setupWebSocket();
    }

    setupWebSocket() {
        this.wss.on('connection', async (ws, req) => {
            const deviceId = this.extractDeviceId(req);
            if (!deviceId) {
                ws.close(4001, 'No device ID provided');
                return;
            }

            this.handleDeviceConnection(ws, deviceId);
        });
    }

    async handleDeviceConnection(ws, deviceId) {
        // 注册设备连接
        this.connections.set(deviceId, {
            ws,
            connectedAt: new Date(),
            clients: new Set()
        });

        // 更新设备状态
        await this.redis.set(`device:${deviceId}:status`, 'connected');

        ws.on('message', (data) => {
            this.handleDeviceMessage(deviceId, data);
        });

        ws.on('close', () => {
            this.handleDeviceDisconnection(deviceId);
        });
    }

    async handleDeviceMessage(deviceId, data) {
        try {
            const device = this.connections.get(deviceId);
            if (!device) return;

            // 广播消息给所有已授权的客户端
            device.clients.forEach(client => {
                if (client.readyState === WebSocket.OPEN) {
                    client.send(data);
                }
            });

            // 存储重要数据
            await this.storeDeviceData(deviceId, data);
        } catch (error) {
            console.error(`Error handling device message: ${error}`);
        }
    }

    async handleDeviceDisconnection(deviceId) {
        const device = this.connections.get(deviceId);
        if (!device) return;

        // 通知所有连接的客户端
        device.clients.forEach(client => {
            client.send(JSON.stringify({
                type: 'device_disconnected',
                deviceId
            }));
        });

        // 更新设备状态
        await this.redis.set(`device:${deviceId}:status`, 'disconnected');
        this.connections.delete(deviceId);
    }
}
